<template>
  <el-dialog
    :title="title"
    v-model="visible"
    width="480px"
    append-to-body
    destroy-on-close
	:close-on-click-modal="false"
	:draggable="true"
	@closed="handleClose"
  >
  
    <div>
        <el-form 
          ref="formRef"
          :model="formModel" 
          :rules="rules"
          label-width="120px" 
          label-position="top"
        >
			
          <el-form-item label="名称" prop="name">
            <el-input v-model="formModel.name" placeholder="属性名称" />
          </el-form-item>
			
          <el-form-item label="标识符" prop="identifier">
            <el-input v-model="formModel.identifier" placeholder="属性唯一标识符" />
          </el-form-item>

          <el-form-item label="数据类型" prop="dataType.type" required>
            <el-select v-model="formModel.dataType.type" @change="handleTypeChange">
              <el-option label="整数" value="int" />
              <el-option label="浮点数" value="float" />
              <el-option label="双精度" value="double" />
              <el-option label="文本" value="text" />
              <el-option label="日期" value="date" />
              <el-option label="布尔" value="bool" />
              <el-option label="枚举" value="enum" />
              <el-option label="结构体" value="struct" />
              <el-option label="数组" value="array"/>
            </el-select>
          </el-form-item>

          <!-- 数值类型特有属性 -->
          <template v-if="['int', 'float', 'double'].includes(formModel.dataType.type)">
            <div class="data-range">
              <span class="data-range-label">取值范围</span>
              <div class="data-range-inputs">
                <el-input-number
                  v-model="formModel.dataType.specs.min"
                  placeholder="最小值"
                  class="range-input"
                  :max="formModel.dataType.specs.max"
                />
                <span class="range-separator">~</span>
                <el-input-number
                  v-model="formModel.dataType.specs.max"
                  placeholder="最大值"
                  class="range-input"
                  :min="formModel.dataType.specs.min"
                />
              </div>
            </div>
            <el-form-item label="步长" prop="dataType.specs.step" required>
              <el-input-number v-model="formModel.dataType.specs.step" :min="0" />
            </el-form-item>
            <el-form-item label="单位" prop="dataType.specs.unit">
              <el-select v-model="formModel.dataType.specs.unit" placeholder="请选择单位">
                <el-option label="米" value="m" />
                <el-option label="千米" value="km" />
                <el-option label="厘米" value="cm" />
              </el-select>
            </el-form-item>
          </template>

          <!-- 文本类型特有属性 -->
          <template v-if="formModel.dataType.type === 'text'">
            <el-form-item label="最大长度" prop="dataType.specs.length" required>
              <el-input-number v-model="formModel.dataType.specs.length" :min="1" :max="10240" />
            </el-form-item>
          </template>

          <!-- 布尔类型特有属性 -->
          <template v-if="formModel.dataType.type === 'bool'">
			<div>
				<div style="margin-bottom: 8px;">
					<span style="color: #d93026;line-height: 10px;padding-right: 5px;">*</span><span>布尔值</span>
				</div>
				<div style="display: flex;align-items: baseline;justify-content: flex-start;">
					<div style="margin-right: 8px;width: 18px;">
						<span>0 - </span>
					</div>
					<div style="width: calc(100% - 26px);">
						<el-form-item prop="dataType.specs.0" :rules="{ required: true, message: '请输入布尔值0的含义' }">
						  <el-input v-model="formModel.dataType.specs['0']" placeholder="如:关" />
						</el-form-item>
					</div>
				</div>
				
				<div style="display: flex;align-items: baseline;justify-content: flex-start;">
					<div style="margin-right: 8px;width: 18px;">
						<span>1 - </span>
					</div>
					<div style="width: calc(100% - 26px);">
						<el-form-item prop="dataType.specs.1" :rules="{ required: true, message: '请输入布尔值1的含义' }">
						  <el-input v-model="formModel.dataType.specs['1']" placeholder="如:开" />
						</el-form-item>
					</div>
				</div>
			</div>  
          </template>

          <!-- 数组类型特有属性 -->
          <template v-if="formModel.dataType.type === 'array'">
            <el-form-item label="元素个数" prop="dataType.specs.size">
              <el-input-number 
                v-model="formModel.dataType.specs.size" 
                :min="1" 
                :max="512"
                placeholder="请输入元素个数"
              />
            </el-form-item>
            <el-form-item label="元素类型" prop="dataType.specs.item.type">
              <el-radio-group v-model="formModel.dataType.specs.item.type" @change="handleItemTypeChange" class="flex-container">
                <el-radio :value="'int32'">int32</el-radio>
                <el-radio :value="'float'">float</el-radio>
                <el-radio :value="'double'">double</el-radio>
                <el-radio :value="'text'">text</el-radio>
                <el-radio :value="'struct'">struct</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>

          <!-- 结构体参数列表 -->
          <template v-if="showStructParams">
            <div class="struct-params-content">
              <div class="struct-header">
                <span class="struct-title">结构体参数</span>
                <div class="struct-info">
                  <span class="param-count">参数数量：{{ formModel.dataType.specs?.length || 0 }}</span>
                  <el-button type="primary" link @click="handleAddStructParam">
                    <el-icon><Plus /></el-icon>添加参数
                  </el-button>
                </div>
              </div>
              <div class="struct-params-list">
                <div v-for="(item, index) in formModel.dataType.specs" :key="index" class="struct-params-list-row">
                  <div class="param-info">
                    <div class="param-name">{{ item.name }}</div>
                    <div class="param-detail">
                      <span>标识符: {{ item.identifier }}</span>
                      <span>类型: {{ item.dataType.type }}</span>
                    </div>
                  </div>
                  <div class="param-actions">
                    <el-button type="primary" link @click="handleEditStructParam(index,item)">
                      <el-icon><Edit /></el-icon>编辑
                    </el-button>
                    <el-button type="danger" link @click="handleDeleteStructParam(index)">
                      <el-icon><Delete /></el-icon>删除
                    </el-button>
                  </div>
                </div>
                <div v-if="!formModel.dataType.specs?.length" class="empty-tip">
                  暂无参数，请点击上方"添加参数"按钮添加
                </div>
              </div>
            </div>
          </template>
		  
		  <template v-if="showArrayStructParams">
		    <div class="struct-params-content">
		      <div class="struct-header">
		        <span class="struct-title">JSON 对象</span>
		        <div class="struct-info">
		          <span class="param-count">参数数量：{{ formModel.dataType.specs.item.specs?.length || 0 }}</span>
		          <el-button type="primary" link @click="handleAddStructParam">
		            <el-icon><Plus /></el-icon>添加参数
		          </el-button>
		        </div>
		      </div>
		      <div class="struct-params-list">
		        <div v-for="(item, index) in formModel.dataType.specs.item.specs" :key="index" class="struct-params-list-row">
		          <div class="param-info">
		            <div class="param-name">{{ item.name }}</div>
		            <div class="param-detail">
		              <span>标识符: {{ item.identifier }}</span>
		              <span>类型: {{ item.dataType.type }}</span>
		            </div>
		          </div>
		          <div class="param-actions">
		            <el-button type="primary" link @click="handleEditStructParam(index,item)">
		              <el-icon><Edit /></el-icon>编辑
		            </el-button>
		            <el-button type="danger" link @click="handleDeleteStructParam(index)">
		              <el-icon><Delete /></el-icon>删除
		            </el-button>
		          </div>
		        </div>
		        <div v-if="!formModel.dataType.specs.item.specs?.length" class="empty-tip">
		          暂无参数，请点击上方"添加参数"按钮添加
		        </div>
		      </div>
		    </div>
		  </template>

          <!-- 枚举类型特有属性 -->
          <template v-if="formModel.dataType.type === 'enum'">
            <div class="dataType-enum-content">
              <div class="enum-header">
                <span class="enum-title">枚举项</span>
                <el-button type="primary" link @click="addEnumItem">
                  <el-icon><Plus /></el-icon>添加枚举项
                </el-button>
              </div>
              <div>
                <div v-for="(value, key) in formModel.dataType.specs" :key="key">
                  <div style="display: flex;align-items: baseline;justify-content: flex-start;margin-bottom: 16px;">
                    <div style="margin-right: 8px;width: 120px;">
                      <el-input 
                        v-model="enumKeys[key]" 
                        placeholder="参数值"
                        style="width: 100px;"
                        @blur="validateEnumKey(key)"
                        @change="handleEnumKeyChange(key)"
                        :status="enumKeyErrors[key] ? 'error' : ''"
                      />
                      <div v-if="enumKeyErrors[key]" class="enum-key-error">
                        {{ enumKeyErrors[key] }}
                      </div>
                      <span style="margin: 0 4px;">-</span>
                    </div>
                    <div style="flex: 1;">
                      <el-form-item 
                        :prop="`dataType.specs.${key}`"
                        :rules="[
                          { required: true, message: '请输入枚举描述', trigger: 'blur' },
                          { 
                            pattern: /^[\u4e00-\u9fa5a-zA-Z0-9][\u4e00-\u9fa5a-zA-Z0-9_\-\u3040-\u309F\u30A0-\u30FF]{0,19}$/,
                            message: '支持中文、英文大小写、日文、数字、下划线和短划线，必须以中文、英文或数字开头，不超过20个字符',
                            trigger: 'blur'
                          }
                        ]"
                        label-width="0"
                      >
                        <el-input
                          v-model="formModel.dataType.specs[key]"
                          placeholder="参数描述"
                        />
                      </el-form-item>
                    </div>
                    <el-button type="danger" link @click="removeEnumItem(key)">
                      <el-icon><Delete /></el-icon>删除
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </template>
		  
		  <el-form-item label="读写类型" prop="accessMode" required>
		    <el-radio-group v-model="formModel.accessMode" class="flex-container">
		      <el-radio :value="'r'">只读</el-radio>
		      <el-radio :value="'rw'">读写</el-radio>
		    </el-radio-group>
		  </el-form-item>

          <el-form-item label="默认值" prop="defaultValue">
            <el-input v-model="formModel.defaultValue" :placeholder="getDefaultValuePlaceholder(formModel.dataType.type)" />
          </el-form-item>
        </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 结构体参数编辑对话框 -->
  <param-definition-dialog
	v-if="definitionParamDialog.visible"
    :visible="definitionParamDialog.visible"
	:index="definitionParamDialog.index"
    :title="definitionParamDialog.title"
    :param="definitionParamDialog.form"
    @success="handleStructParamConfirm"
	@closed="handleStructParamClosed"
  />
</template>

<script setup lang="ts">
	import { ref, watch, computed, reactive, nextTick } from 'vue';
	import { ElMessage, ElMessageBox } from 'element-plus';
	import { Plus, Delete, Edit } from '@element-plus/icons-vue';
	import type { ParamDefinition, NumberSpecsDefinition, BoolSpecsDefinition,TextSpecsDefinition,ArraySpecsItemDefinition,EnumSpecsDefinition,DataTypeDefinition,ArraySpecsDefinition } from '@/api/biz/parammodel';
	import type { FormInstance } from 'element-plus'
	
	const props = defineProps({
	  visible: {
		type: Boolean,
		required: true
	  },
	  title: {
		type: String,
		required: true
	  },
	  index: {
		type: Number,
		required: true
	  },
	  param: {
		type: Object as () => ParamDefinition,
		required: true
	  }
	});

	const emit = defineEmits(['success', 'closed']);

	const visible = ref(false);

	const formModel = ref<ParamDefinition>({
		identifier: '',
		name: '',
		accessMode: 'r',
		required: false,
		dataType: {
			type: 'text',
			specs: undefined
		},
		defaultValue: ''
	});

	const definitionParamDialog = reactive<any>({
	  visible: false,
	  index: 0,
	  title:"",
	  form:{
	  }
	});
	
	const showStructParams = computed(() => {
	  return formModel.value.dataType.type === 'struct' ;
	});
	
	const showArrayStructParams = computed(() => {
	  return (formModel.value.dataType.type === 'array' && formModel.value.dataType.specs.item?.type === 'struct');
	});
	

	const formRef = ref<FormInstance>()
	
	// 类型定义
	type DataType = 'int' | 'float' | 'double' | 'text' | 'date' | 'bool' | 'enum' | 'struct' | 'array';

	// 基础验证规则
	const baseRules = {
	  name: [
		{ required: true, message: '请输入参数名称', trigger: 'blur' },
		{ min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
	  ],
	  identifier: [
		{ required: true, message: '请输入参数标识符', trigger: 'blur' },
		{ pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '标识符必须以字母开头，只能包含字母、数字和下划线', trigger: 'blur' }
	  ],
	  'dataType.type': [
		{ required: true, message: '请选择数据类型', trigger: ['blur', 'change'] }
	  ],
	  accessMode: [
		{ required: true, message: '请选择读写类型', trigger: ['blur', 'change'] }
	  ],
	  defaultValue: [
		{ required: false }
	  ]
	};

	// 获取类型特定的验证规则
	const getSpecsRules = (type: DataType) => {
	  switch(type) {
		case 'int':
		case 'float':
		case 'double':
		  return {
			'dataType.specs.step': [
			  { required: true, message: '请输入步长', trigger: ['blur', 'change'] }
			]
		  };
		case 'text':
		  return {
			'dataType.specs.length': [
			  { required: true, message: '请输入最大长度', trigger: ['blur', 'change'] }
			]
		  };
		case 'bool':
		  return {
			'dataType.specs.0': [
			  { required: true, message: '请输入布尔值0的含义', trigger: ['blur', 'change'] }
			],
			'dataType.specs.1': [
			  { required: true, message: '请输入布尔值1的含义', trigger: ['blur', 'change'] }
			]
		  };
		case 'array':
		  return {
			'dataType.specs.size': [
			  { required: true, message: '请输入元素个数', trigger: ['blur', 'change'] }
			],
			'dataType.specs.item.type': [
			  { required: true, message: '请选择元素类型', trigger: ['blur', 'change'] }
			]
		  };
		default:
		  return {};
	  }
	};

	const rules = computed(() => {
	  return {
		...baseRules,
		...getSpecsRules(formModel.value.dataType.type as DataType)
	  };
	});

	const enumKeys = ref<Record<any, any>>({});
	const enumKeyErrors = ref<Record<any, any>>({});

	const DEFAULT_PARAM: ParamDefinition = {
	  identifier: '',
	  name: '',
	  accessMode: 'r',
	  required: false,
	  dataType: {
		type: 'text',
		specs: undefined
	  },
	  defaultValue: ''
	};

	const DEFAULT_STRUCT_PARAM: ParamDefinition = {
	  identifier: '',
	  name: '',
	  accessMode: 'rw',
	  required: false,
	  dataType: {
		type: 'text',
		specs: undefined
	  },
	  defaultValue: ''
	};

	watch(() => props.visible, (val) => {
	    visible.value = val;
		if (val) {
			formModel.value = props.param;
			if (formModel.value.dataType.type === 'enum' && formModel.value.dataType.specs) {
			  enumKeys.value = {};
			  enumKeyErrors.value = {};
			  Object.keys(formModel.value.dataType.specs).forEach(key => {
				enumKeys.value[key] = key;
			  });
			}
			console.log(formModel.value);
		}
	},{ immediate: true, deep: true });
	
	const handleTypeChange = () => {
		// 根据类型初始化对应的 specs
		switch(formModel.value.dataType.type as DataType) {
		  case 'int':
		  case 'float':
		  case 'double':
			formModel.value.dataType.specs = {
			  min: undefined,
			  max: undefined,
			  step: 1,
			  unit: undefined
			} as NumberSpecsDefinition;
			break;
		  case 'text':
			formModel.value.dataType.specs = {
			  length: 255
			} as TextSpecsDefinition;
			break;
		  case 'bool':
			formModel.value.dataType.specs = {
			  '0': '',
			  '1': ''
			} as BoolSpecsDefinition;
			break;
		  case 'enum':
			formModel.value.dataType.specs = {} as EnumSpecsDefinition;
			enumKeys.value = {};
			enumKeyErrors.value = {};
			addEnumItem();
			break;
		  case 'array':
			formModel.value.dataType.specs = {
				size: 10,
				item:{
					type: 'int32',
					specs:[]
				}
			} as unknown as ArraySpecsDefinition;
			break;
		  case 'struct':
			formModel.value.dataType.specs = [] as ParamDefinition[];
			break;
		  default:
			formModel.value.dataType.specs = undefined;
		}
		formModel.value.defaultValue = '';
		// 重置表单验证
		nextTick(() => {
		  formRef.value?.clearValidate();
		});
	};

	const handleItemTypeChange = () => {
	  if (formModel.value.dataType.type === 'array') {
		if(formModel.value.dataType.specs.item.type=='struct'){
			formModel.value.dataType.specs.item.specs=[];
		}else{
			if(formModel.value.dataType.specs.item.specs){
				delete formModel.value.dataType.specs.item.specs
			}
		}
	  }
	};

	const getDefaultValuePlaceholder = (type: string) => {
	  switch (type) {
		case 'int':
		case 'float':
		case 'double':
		  return '请输入数字';
		case 'text':
		  return '请输入文本';
		case 'date':
		  return '请输入UTC毫秒时间戳';
		case 'bool':
		  return '请输入0或1';
		case 'enum':
		  return '请输入枚举值';
		case 'array':
		case 'struct':
		  return '请输入JSON格式数据';
		default:
		  return '';
	  }
	};

	const validateEnumKey = (key: string|number) => {
	  const value = enumKeys.value[key];
	  enumKeyErrors.value[key] = '';
	  
	  if (!value) {
		enumKeyErrors.value[key] = '请输入枚举值';
		return false;
	  }
	  
	  // 验证是否为整数
	  const intValue = parseInt(value);
	  if (isNaN(intValue) || intValue.toString() !== value) {
		enumKeyErrors.value[key] = '枚举值必须为整数';
		return false;
	  }
	  
	  // 验证取值范围
	  if (intValue < -2147483648 || intValue > 2147483647) {
		enumKeyErrors.value[key] = '枚举值范围：-2147483648 ~ 2147483647';
		return false;
	  }
	  
	  const keys = Object.keys(enumKeys.value);
	  const duplicateKey = keys.find(k => k !== key && enumKeys.value[k] === value);
	  if (duplicateKey) {
		enumKeyErrors.value[key] = '枚举值不能重复';
		return false;
	  }
	  
	  return true;
	};

	const handleEnumKeyChange = (oldKey: string|number) => {
	  const newKey = enumKeys.value[oldKey];
	  if (!newKey) {
		enumKeyErrors.value[oldKey] = '枚举值不能为空';
		enumKeys.value[oldKey] = oldKey;
		return;
	  }
	  
	  // 验证是否为整数
	  const intValue = parseInt(newKey);
	  if (isNaN(intValue) || intValue.toString() !== newKey) {
		enumKeyErrors.value[oldKey] = '枚举值必须为整数';
		enumKeys.value[oldKey] = oldKey;
		return;
	  }
	  
	  // 验证取值范围
	  if (intValue < -2147483648 || intValue > 2147483647) {
		enumKeyErrors.value[oldKey] = '枚举值范围：-2147483648 ~ 2147483647';
		enumKeys.value[oldKey] = oldKey;
		return;
	  }
	  
	  const keys = Object.keys(enumKeys.value);
	  const duplicateKey = keys.find(k => k !== oldKey && enumKeys.value[k] === newKey);
	  if (duplicateKey) {
		enumKeyErrors.value[oldKey] = '枚举值不能重复';
		enumKeys.value[oldKey] = oldKey;
		return;
	  }
	  
	  enumKeyErrors.value[oldKey] = '';
	  
	  if (newKey && newKey !== oldKey) {
		const value = formModel.value.dataType.specs[oldKey];
		delete formModel.value.dataType.specs[oldKey];
		formModel.value.dataType.specs[newKey] = value;
		enumKeys.value[newKey] = newKey;
		delete enumKeys.value[oldKey];
		delete enumKeyErrors.value[oldKey];
	  }
	};

	const handleSubmit = async () => {
	  try {
		await formRef.value?.validate();
		const paramData = JSON.parse(JSON.stringify(formModel.value));
		
		// 验证 specs
		if (!validateSpecs(paramData)) {
		  return;
		}

		// 类型检查和数据清理
		switch(paramData.dataType.type as DataType) {
		  case 'int':
		  case 'float':
		  case 'double':
			const numSpecs = paramData.dataType.specs as NumberSpecsDefinition;
			if (!numSpecs.min && !numSpecs.max && !numSpecs.step && !numSpecs.unit) {
			  paramData.dataType.specs = undefined;
			}
			break;
		  case 'text':
			const textSpecs = paramData.dataType.specs as TextSpecsDefinition;
			if (!textSpecs.length) {
			  paramData.dataType.specs = undefined;
			}
			break;
		}

		if (paramData.dataType.type === 'enum') {
		  const enumSpecs = paramData.dataType.specs as EnumSpecsDefinition;
		  const enumItems = Object.keys(enumSpecs || {});
		  if (enumItems.length === 0) {
			ElMessage.warning('请至少添加一个枚举项');
			return;
		  }
		  
		  let hasError = false;
		  for (const key of enumItems) {
			if (!validateEnumKey(key)) {
			  hasError = true;
			}
			if (!paramData.dataType.specs?.[key]) {
			  ElMessage.warning('请填写完整的枚举描述');
			  return;
			}
		  }
		  if (hasError) {
			return;
		  }
		}
		emit('success', props.index, paramData);
		handleClose();
	  } catch (error) {
		console.log('表单验证失败:', error);
	  }
	};

	const handleClose = () => {
	  visible.value = false;
	  formRef.value?.resetFields();
	  formModel.value = {
		identifier: '',
		name: '',
		accessMode: 'rw',
		required: false,
		dataType: {
		type: 'text',
			specs: {}
		},
		defaultValue: ''
	  };
	  enumKeys.value = {};
	  enumKeyErrors.value = {};
	  emit('closed');
	};

	const addEnumItem = () => {
	  if (!formModel.value.dataType.specs) {
		formModel.value.dataType.specs = {};
	  }
	  const keys = Object.keys(formModel.value.dataType.specs);
	  const newKey = keys.length > 0 ? 
		(Math.max(...keys.map(Number).filter(n => !isNaN(n))) + 1).toString() : 
		'0';
	  formModel.value.dataType.specs[newKey] = '';
	  enumKeys.value[newKey] = newKey;
	};

	const removeEnumItem = (key: string|number) => {
	  if (!formModel.value.dataType.specs) return;
	  delete formModel.value.dataType.specs[key];
	  delete enumKeys.value[key];
	  delete enumKeyErrors.value[key];
	};
	
	const tempParamDefinitions = ref<ParamDefinition>({
	  identifier: '',
	  name: '',
	  accessMode: 'rw',
	  required: false,
	  dataType: {
	    type: 'text',
	    specs: {}
	  },
	  defaultValue: ''
	});
	

	/**
	 * 添加
	 */
	const handleAddStructParam = () => {
		definitionParamDialog.index = -1;
		definitionParamDialog.form = {
		};
		definitionParamDialog.title="新增参数字段"
		definitionParamDialog.visible = true;
	};

	const handleEditStructParam = (index: number,data:any) => {
	  definitionParamDialog.index=index;
	  definitionParamDialog.form=data;
	  definitionParamDialog.title="编辑参数字段";
	  definitionParamDialog.visible=true;

	};
	
	const handleStructParamConfirm = (index: number, paramData: ParamDefinition) => {
		try {
			if((formModel.value.dataType.type === 'array' && formModel.value.dataType.specs.item?.type === 'struct')){
				
				if (!formModel.value.dataType.specs.item.specs) {
					formModel.value.dataType.specs.item.specs = [];
				}
				if (index > -1) {
					formModel.value.dataType.specs.item.specs[index] = paramData;
				} else {
					formModel.value.dataType.specs.item.specs.push(paramData);
				}
			}else{
				if (!formModel.value.dataType.specs) {
					formModel.value.dataType.specs = [];
				}
				if (index > -1) {
					formModel.value.dataType.specs[index] = paramData;
				} else {
					formModel.value.dataType.specs.push(paramData);
				}
			}
			handleStructParamClosed();
		} catch (e:any) {
			ElMessage.error(e.message);
		}
	};

	/**
	 * 关闭弹出
	 */
	const handleStructParamClosed = () => {
		definitionParamDialog.index=-1;
		definitionParamDialog.form={
		};
		definitionParamDialog.title="";
		definitionParamDialog.visible=false;
	};

	const handleDeleteStructParam = (index: number) => {
	  ElMessageBox.confirm('确认删除该参数吗？', '提示', {
		type: 'warning'
	  }).then(() => {
		if(showArrayStructParams){
			const params = formModel.value.dataType.specs.item.specs;
			if (params) {
			  params?.splice(index, 1);
			  ElMessage.success('删除成功');
			}
		}
		else if(showStructParams){
			const params = formModel.value.dataType.specs;
			if (params) {
			  params?.splice(index, 1);
			  ElMessage.success('删除成功');
			}
		}
	  });
	};

	const validateSpecs = (paramData: ParamDefinition): boolean => {
	  switch(paramData.dataType.type as DataType) {
		case 'int':
		case 'float':
		case 'double':
		  const numSpecs = paramData.dataType.specs as NumberSpecsDefinition;
		  if (!numSpecs?.step) {
			ElMessage.warning('请输入步长');
			return false;
		  }
		  break;
		case 'text':
		  const textSpecs = paramData.dataType.specs as TextSpecsDefinition;
		  if (!textSpecs?.length) {
			ElMessage.warning('请输入最大长度');
			return false;
		  }
		  break;
		case 'bool':
		  const boolSpecs = paramData.dataType.specs as BoolSpecsDefinition;
		  if (!boolSpecs?.['0'] || !boolSpecs?.['1']) {
			ElMessage.warning('请输入布尔值的含义');
			return false;
		  }
		  break;
		case 'array':
			if(paramData.dataType?.specs?.item.type=='struct'){
			  if (paramData.dataType.specs.item.specs==undefined || paramData.dataType.specs?.item.specs?.length==0) {
					ElMessage.warning('Json对象必填.');
					return false;
			}
		  }
		  break;
	  }
	  return true;
	};
</script>

<style lang="scss" scoped>
.param-dialog-content {
  max-height: calc(80vh - 150px);
  overflow-y: auto;
  padding: 0 20px;
}

.param-model-content-item {
  margin-bottom: 24px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
}

.param-model-content-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: var(--el-fill-color);
  border-bottom: 1px solid var(--el-border-color-light);
}

.param-model-form {
  padding: 16px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;

  :deep(.el-form-item) {
    margin-bottom: 18px;
  }
}

.dialog-footer {
  text-align: right;
}

.dataType-enum-content {
  margin: 0 0 16px;
  padding: 16px;
  background-color: var(--el-fill-color);
  border-radius: 4px;
}

.enum-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.enum-title {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.enum-row {
  margin-bottom: 8px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.enum-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.enum-value {
  width: 120px;
}

.enum-separator {
  color: var(--el-text-color-secondary);
  margin: 0 4px;
}

.enum-desc {
  flex: 1;
}

.section-title {
  margin: 24px 0 16px;
  
  &:first-child {
    margin-top: 0;
  }
}

.title-form_primary {
  font-weight: 500;
  font-size: 14px;
  color: #1f2329;
  position: relative;
  padding-left: 12px;
  
  &:before {
    content: "";
    width: 2px;
    height: 14px;
    background: var(--el-color-primary);
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    left: 0;
  }
}

.data-range {
  margin-bottom: 18px;
}

.data-range-label {
  color: var(--el-text-color-regular);
  margin-right: 12px;
}

.data-range-inputs {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
}

.range-input {
  width: 160px;
}

.range-separator {
  color: var(--el-text-color-secondary);
}

.el-radio-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.el-radio {
  height: 32px;
  line-height: 32px;
  margin-right: 0;
}

.struct-params-content {
  margin: 0 0 16px;
  padding: 16px;
  background-color: var(--el-fill-color);
  border-radius: 4px;
}

.struct-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.struct-title {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.struct-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.param-count {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.struct-params-list {
  .struct-params-list-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    margin-bottom: 8px;
    background: var(--el-bg-color);
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 4px;
    transition: all 0.3s;
    
    &:hover {
      border-color: var(--el-border-color);
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }
    
    .param-info {
      flex: 1;
      
      .param-name {
        font-size: 14px;
        font-weight: 500;
        color: var(--el-text-color-primary);
        margin-bottom: 4px;
      }
      
      .param-detail {
        display: flex;
        align-items: center;
        gap: 16px;
        color: var(--el-text-color-secondary);
        font-size: 13px;
      }
    }
    
    .param-actions {
      display: flex;
      gap: 8px;
    }
  }
  
  .empty-tip {
    text-align: center;
    color: var(--el-text-color-secondary);
    padding: 32px 0;
  }
}
.flex-container {
	display: flex;
	flex-direction: row;
}
.flex-container .el-radio {
  margin-right: 10px; /* 根据需要调整间距 */
}

.enum-key-error {
  position: absolute;
  font-size: 12px;
  color: var(--el-color-danger);
  margin-top: 2px;
}

.el-input.is-error {
  .el-input__wrapper {
    box-shadow: 0 0 0 1px var(--el-color-danger) inset;
  }
}
</style> 